<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Model\SocialAccount;
use App\Model\User;

/**
 * 绑定QQ和微信登录
 */
class BindSocialService extends AuthBaseService
{
    protected $socialProvider = [
        1 => 'qq',
        2 => 'weixin',
    ];

    protected function RoVerifyList()
    {
        return [
            'provider' => "required|string",
            'openid' => "required|string"
        ];
    }

    public function handle()
    {
        $provider = $this->request->input('provider');
        $openId = $this->request->input('openid');
        $userId = $this->getUserId();

        if (!in_array($provider, $this->socialProvider)) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '渠道无效！');
        }

        //是否存在第三方注册账号
        $socialAccount = SocialAccount::check($provider, $openId);

        //返回数组
        $ret = ['result' => 1];
        //已绑定了第三方账号
        if ($socialAccount && $socialAccount->user) {
            log_user_result($userId, "SocialBinded:{$socialAccount->user->id}");
            $providerName = $provider == 'weixin' ? '微信' : 'QQ';
            return $this->setError(ErrorCode::SOCIAL_BINDED, "该{$providerName}已经绑定了其他账号！");
        }

        //是否绑定
        $socialUser = SocialAccount::checkUser($provider, $userId);
        //若已经绑定,则重新绑定
        if ($socialUser) {
            SocialAccount::where(['provider' => $provider, 'user_id' => $userId])->limit(1)->update([
                'provider' => $provider,
                'provider_user_id' => $openId,
            ]);
        } else {
            //新建第三方绑定
            SocialAccount::createAccount($userId, $provider, $openId);
        }
        return $ret;
    }
}
